package com.atguigu.tingshu.user.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.atguigu.tingshu.user.config.properties.WxAutoProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;

/**
 *
 */
@Configuration
@EnableConfigurationProperties(WxAutoProperties.class)
public class WxAppAutoConfiguration {
    @Autowired
    WxAutoProperties wxAutoProperties;
    @Bean
    public WxMaService wxMaService() {

        WxMaService wxMaService = new WxMaServiceImpl();
        WxMaDefaultConfigImpl wxMaDefaultConfig = new WxMaDefaultConfigImpl();
        wxMaDefaultConfig.setAppid(wxAutoProperties.getAppId());
        wxMaDefaultConfig.setSecret(wxAutoProperties.getAppSecret());
        wxMaService.setWxMaConfig(wxMaDefaultConfig);

        return wxMaService;
    }

//    //读取证书

//    @Bean
//    public RsaSigner rsaSigner() {
//        ClassPathResource classPathResource = new ClassPathResource("tingshu.jks");
//        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "tingshu".toCharArray());
//        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("tingshu", "tingshu".toCharArray());
//        RSAPrivateKey aPrivate = (RSAPrivateKey) keyPair.getPrivate();
//        RsaSigner rsaSigner = new RsaSigner(aPrivate);
//        return rsaSigner;
//    }
    @Bean
    public RsaSigner rsaSigner(){
        //读取
        ClassPathResource classPathResource = new ClassPathResource("tingshu.jks");
        //创建工厂对象
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "tingshu".toCharArray());
        //获取钥匙对
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("tingshu", "tingshu".toCharArray());
        //获取私钥
        RSAPrivateKey  aPrivate =(RSAPrivateKey) keyPair.getPrivate();
        RsaSigner rsaSigner = new RsaSigner(aPrivate);
        return rsaSigner;
    }
}
